﻿@model Yamfinder.Web.Models.ImportMappingsModel

@{
    ViewBag.Title = "Mappings";
}

<h2>Mappings</h2>
    
<table>
    <tr>
        <th>Column Name</th>
        <th>Column Type</th>
        <th>Existing Fields</th>
        <th>Mapped Field</th>
        <th>Action to Take</th>
    </tr>
    @for (var i = 0; i < Model.Mappings.Count; i++)
    {
        @Html.Partial("Mapping", Model.Mappings[i])
    }
</table>
    
<span>
    <input type="button" value="Process Data" id="submitButton" />
    <input type="button" value="Cancel" id="cancelButton" />
</span>
    


<script type="text/javascript">
    $(document).ready(function () {

        $(".existingSelector").click(function () {
            if ($(this).size() <= 1) {
                var id = $(this).attr("id");
                var selectedValue = $(this).val();
                setValue(id, selectedValue);
            }
        });

        $(".existingSelector").change(function () {
            var id = $(this).attr("id");
            var selectedValue = $(this).val();
            setValue(id, selectedValue);
        });

        $(".mappedField").keyup(function () {
            var id = $(this).attr("id");
            id = id.substring(0, id.indexOf("_"));
            $("#" + id + "_action").text("Create a new field - '" + $(this).val() + "'");
        });

        $(".specialHeaderThing").click(function () {
            var id = $(this).attr("id");
            id = id.substring(0, id.indexOf("_"));
            var value = $(this).text();
            setNewField(id, value);
        });

        $("#cancelButton").click(function () {
            window.location = "/Import/Index";
        });

        $("#submitButton").click(function () {

            var json = {};

            json['Id'] = "@Model.Id";

            $(".existingSelector").each(function (index) {
                var id = $(this).attr("id");

                var importName = id;
                var databaseName = $("#" + id + "_textBox").val();
                var type = $("#" + id + "_importType").text();

                json['Mappings[' + index + '].DatabaseName'] = databaseName;
                json['Mappings[' + index + '].ImportName'] = importName;
                json['Mappings[' + index + '].Type'] = type;
            });

            $.post('@Url.Action("Mappings")', json, function (result) {
                $.html(result);
            });
        });

    });

    function setValue(id, value) {
        $("#" + id + "_textBox").val(value);
        $("#" + id + "_action").text("Map to existing database field - '" + value + "'");
    }

    function setNewField(id, value) {
        $("#" + id + "_textBox").val(value);
        $("#" + id + "_action").text("Create a new field - '" + value + "'");
    }

</script>

